package com.ficv.tucanalmovil.web;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class UserServiceImpl implements UserDetailsService {
	 
	
	private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

	
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
     
        List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();
         

         
            AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_USER"));
            

			try {
            
            return new User(username,
            		getPwd(username),
                     AUTHORITIES);
            
    		}	catch (Throwable e) {
				e.printStackTrace();
				throw new UsernameNotFoundException("Ususario no aceptado: " + username);
			} 
			
//        } else if (username.equals("scott")){
//             
//            AUTHORITIES.add(new SimpleGrantedAuthority("user"));
//            return new User("scott",
//                    "fb1f9e48058d30dc21c35ab4cf895e2a80f2f03fac549b51be637196dfb6b2b7276a89c65e38b7a1",
//                     AUTHORITIES);
//        }
//        else
//        {
//            throw new UsernameNotFoundException("User not found: " + username);
//        }
         
    }

	public static String getPwd(String username) throws NoSuchAlgorithmException {
		MessageDigest messageDigest;
		messageDigest = MessageDigest.getInstance("SHA-256");
 
		try {
			int userInt=Integer.parseInt(username);
			if(userInt>0 && userInt < 10) return String.valueOf(userInt);
		} catch(Throwable e) {
			
		}
         messageDigest.update(getHash(username));
         byte[] encryptedString = messageDigest.digest();
         
         StringBuffer sb = new StringBuffer();
         for(byte b : encryptedString) {
        	 sb.append(String.format("%02x", b));
         }
                             
         
		return sb.toString();
	}

	static public byte[] getHash(String username) {
		
		byte[] u = username.getBytes();
		int hash=7;
		
		for (int i=0; i < u.length; i++) {
		    hash = hash*31+u[i];
		}
		
		logger.info("fetching hash id " + hash);
		
		return String.valueOf(hash).getBytes();
	}
}  